<?php

namespace app\common\component;

use think\db\connector\Mongodb;

/**
 * mongodb数据库表操作基类
 * Class Mongo
 * @package app\common\component
 */
class Mongo
{
    static protected $database = '';

    static protected $instanceArr = [];

    public $link;

    private function __construct()
    {
        $this->link = Mongodb::getInstance();
    }

    public static function getInstance($newInstance = false)
    {
        $md5Name = md5(static::class);
        if (!isset(static::$instanceArr[$md5Name]) || $newInstance) {
            static::$instanceArr[$md5Name] = new static();
        }

        return static::$instanceArr[$md5Name];
    }

    /**
     * 添加新数据,返回自增id
     * @param array $data
     * @return int|null
     */
    public function add(array $data)
    {
        return $this->link->insert($this->tableName, $data);
    }

    /**
     * 更新数据
     * @param $data
     * @param $filter
     * @return bool
     */
    public function update($data, $filter)
    {
        return $this->link->set($this->tableName, $data, $filter) > 0 ? true : false;
    }

    /**
     * 返回单个数据
     * @param $filter
     * @return array
     */
    public function find($filter)
    {
        return (array)$this->link->get($this->tableName, $filter);
    }

    /**
     * 返回列表
     * @param $filter
     * @param $sort
     * @param int $skip
     * @param int $limit
     * @return array
     */
    public function pageList($filter, $sort, $skip = 0, $limit = 20)
    {
        $data =  $this->link->select($this->tableName, $filter, $sort, $skip, $limit);
        foreach ($data as &$item) {
            $item = (array)$item;
        }

        return $data;
    }

    /**
     * 删除数据
     * @param $filter
     * @return bool
     */
    public function del($filter)
    {
        return $this->link->delete($this->tableName, $filter) > 0 ? true : false;
    }

    protected function command($cmd)
    {
        $cmd = new \MongoDB\Driver\Command($cmd);
         return $this->link->executeCommand($this->tableName, $cmd);
    }

    /**
     * 统计
     * @param array $filter
     * @return int
     */
    public function count($filter = [])
    {
        $result = $this->link->count($this->tableName, $filter);
        if (isset($result['0']->n)) {
            return $result['0']->n;
        } else {
            return 0;
        }
    }
}